﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DosTexPrj.Core.Models;
using DosTexPrj.Core.RepositoriesInterface;
using DosTexPrj.Implement.NHibernate;
using DosTexPrj.UI.WinForm.Commons;
using DosTexPrj.UI.WinForm.Models;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace DosTexPrj.UI.WinForm
{
    public partial class KnittingOrderForm : Form
    {
        #region -- Private members--

        private IRepository _repository;
        private IOrderRepository _orderRepository;
        private IList<KnittingOrderDetail> _currentOrdersDetail;
        private KnittingOrder _currentOrder;

        #endregion -- Private members--

        #region -- Properties --

        public KnittingOrder CurrentOrder
        {
            private get
            {
                return this._currentOrder;
            }
            set { this._currentOrder = value; }
        }

        private bool ClearForm
        {
            set
            {
                txtDeliveryAddress.Text = string.Empty;
                txtDiameter.Text = string.Empty;
                txtFabricWeight.Text = string.Empty;
                txtGauge.Text = string.Empty;
                txtKnittingMachine.Text = string.Empty;
                txtSupplierAddress.Text = string.Empty;
                txtSupplierName.Text = string.Empty;
                txtSupplierPhone.Text = string.Empty;
                txtWeightEcru.Text = string.Empty;
                txtWeightFinEst.Text = string.Empty;
                txtWhaleCourse.Text = string.Empty;
                txtWidthEcru.Text = string.Empty;
                txtWidthFinEst.Text = string.Empty;
                txtYarnLength.Text = string.Empty;

                dtpOrderDate.Value = DateTime.Now;

                lvOrderDetail.Items.Clear();

                LoadCustomerOrder();
                LoadSupplier();
                LoadFabricType();
                LoadComposition();
                LoadOrderStatus();
            }
        }

        #endregion -- Properties --

        #region -- Constructors --

        public KnittingOrderForm()
        {
            InitializeComponent();
            _repository = MyServiceLocator.DoGetInstance<IRepository>();
            this._orderRepository = MyServiceLocator.DoGetInstance<IOrderRepository>();
            this._currentOrdersDetail = new List<KnittingOrderDetail>();
            this.txtFabricWeight.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtWeightEcru.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtWeightFinEst.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtWidthEcru.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtWidthFinEst.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtYarnLength.KeyPress += new KeyPressEventHandler(Textbox_KeyPress);
            this.txtFabricWeight.MaxLength = this.txtWeightEcru.MaxLength = this.txtWeightFinEst.MaxLength
                = this.txtWidthEcru.MaxLength = this.txtWidthFinEst.MaxLength = this.txtYarnLength.MaxLength = 12;
        }

        public KnittingOrderForm(KnittingOrder orderToEdit)
            : this()
        {
            this._currentOrder = orderToEdit;
        }

        #endregion -- Constructors --

        private void KnittingOrderForm_Load(object sender, EventArgs e)
        {
            LoadOrderList();
            CreateFormTitle();

            LoadFilterSupplier();
            LoadFilterOrderStatus();

            txtSupplierAddress.Enabled = txtSupplierName.Enabled = txtSupplierPhone.Enabled = btnSave.Enabled = false;
        }

        private void Textbox_KeyPress(object sender, KeyPressEventArgs e)
        {
            Common.HandlingNumberTextbox(e);
        }

        #region -- Order List Grid --

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order on Order List for printing", "Warning", MessageBoxButtons.OK);
                return;
            }

            KnittingOrderModel selectedOrderModel = (KnittingOrderModel)lvOrderList.SelectedItems[0].Tag;
            KnittingOrder order = this._repository.FindByKey<KnittingOrder>(selectedOrderModel.Id);
            if (order != null)
            {
                if (!Directory.Exists(@"C:\pdf"))
                {
                    Directory.CreateDirectory(@"C:\pdf");
                }

                string filePath = @"C:\pdf\printing-knittingorder-" + order.Id.ToString() + ".pdf";

                DoPrinting(order, filePath);

                if (File.Exists(filePath))
                {
                    System.Diagnostics.ProcessStartInfo printObject = new System.Diagnostics.ProcessStartInfo();
                    printObject.Verb = "print";
                    printObject.FileName = filePath;
                    printObject.UseShellExecute = true;
                    System.Diagnostics.Process.Start(printObject);
                }
            }
            else
            {
                MessageBox.Show("Please select an Order on Order List for printing", "Warning", MessageBoxButtons.OK);
                return;
            }
        }

        private void lvOrderList_Click(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                return;
            }
            try
            {
                KnittingOrderModel selectedOrderModel = (KnittingOrderModel)lvOrderList.SelectedItems[0].Tag;
                this.CurrentOrder = _repository.FindByKey<KnittingOrder>(selectedOrderModel.Id);
                this._currentOrdersDetail = this.CurrentOrder.Details;
                PushDataToForm(this.CurrentOrder);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
            {
                chkInMonth.Checked = !chkAll.Checked;
                LoadOrderList();
            }
            else
            {
                LoadOrderList();
            }
        }

        private void chkInMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInMonth.Checked)
            {
                chkAll.Checked = !chkInMonth.Checked;
                LoadOrderList();
            }
            else
            {
                LoadOrderList();
            }
        }

        private void dtpOrderMonth_ValueChanged(object sender, EventArgs e)
        {
            LoadOrderList();
        }

        private void cboSupplierFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            chkAll.Checked = chkInMonth.Checked = false;
        }

        #endregion -- Order List Grid --

        #region -- Order detail --

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            ClearForm = true;
            btnSave.Enabled = true;
            this._currentOrder = new KnittingOrder();
            this._currentOrdersDetail = new List<KnittingOrderDetail>();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order on Order List ", "Warning", MessageBoxButtons.OK);
                return;
            }
            try
            {
                KnittingOrderModel selectedOrderModel = (KnittingOrderModel)lvOrderList.SelectedItems[0].Tag;
                if (MessageBox.Show("Are you sure want to delete Order No. " + selectedOrderModel.Id + "?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    _repository.Delete<KnittingOrder>(x => x.Id == selectedOrderModel.Id);
                    LoadOrderList();
                    ClearForm = true;
                    MessageBox.Show("Delete successfully.", "Warning", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValidate())
                return;
            //Kim edited: Do not allow to create Order without OrderDetail
            if (this._currentOrdersDetail == null || this._currentOrdersDetail.Count == 0)
            {
                MessageBox.Show("Please add detail(s) before create order");
                return;
            }
            //End edited by Kim
            this.CreateOrder();
            btnSave.Enabled = false;
            ClearForm = true;
        }

        private void btnAddOrderDetail_Click(object sender, EventArgs e)
        {
            //Kim edited: do not allow add detail if no order was selected
            if (this._currentOrder == null)
            {
                MessageBox.Show("Please select order after add detail");
                return;
            }
            //End edited by Kim
            KnittingOrderDetailForm orderDetailForm = new KnittingOrderDetailForm();
            orderDetailForm.Text = "Add Knitting Order Detail";
            orderDetailForm.FormClosed += new FormClosedEventHandler(orderDetailForm_FormClosed);
            orderDetailForm.StartPosition = FormStartPosition.CenterParent;
            orderDetailForm.ShowDialog();
            LoadOrderDetailList();
        }

        private void orderDetailForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if ((sender as KnittingOrderDetailForm).CurrentOrderDetail == null) return;
            this._currentOrdersDetail.Add((sender as KnittingOrderDetailForm).CurrentOrderDetail);
        }

        private void btnDeleteOrderDetail_Click(object sender, EventArgs e)
        {
            if (lvOrderDetail.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order Detail on Order Detail List ", "Warning", MessageBoxButtons.OK);
                return;
            }
            try
            {
                KnittingOrderDetail selectedOrderDetail = (KnittingOrderDetail)lvOrderDetail.SelectedItems[0].Tag;

                if (MessageBox.Show("Are you sure want to delete this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (selectedOrderDetail.Id != Guid.Empty)
                    {
                        _repository.Delete<KnittingOrderDetail>(x => x.Id == selectedOrderDetail.Id);
                    }
                    this._currentOrdersDetail.Remove(selectedOrderDetail);
                    PushDataToForm(this.CurrentOrder);
                    MessageBox.Show("Delete successfully.", "Warning", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void btnAddSupplier_Click(object sender, EventArgs e)
        {
            SupplierForm supplierForm = new SupplierForm();
            supplierForm.StartPosition = FormStartPosition.CenterParent;
            supplierForm.ShowDialog();
            LoadSupplier();
            LoadFilterSupplier();
        }

        private void btnAddFabricType_Click(object sender, EventArgs e)
        {
            FabricTypeForm fabricTypeForm = new FabricTypeForm();
            fabricTypeForm.StartPosition = FormStartPosition.CenterParent;
            fabricTypeForm.ShowDialog();
            LoadFabricType();
        }

        private void btnAddComposition_Click(object sender, EventArgs e)
        {
            CompositionForm compostionForm = new CompositionForm();
            compostionForm.StartPosition = FormStartPosition.CenterParent;
            compostionForm.ShowDialog();
            LoadComposition();
        }

        private void cboSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            Supplier supplier = (Supplier)cboSupplier.SelectedItem;
            if (supplier != null)
            {
                txtSupplierName.Text = supplier.SupplierName;
                txtSupplierAddress.Text = supplier.Address;
                txtSupplierPhone.Text = supplier.Phone;
            }
        }

        #endregion -- Order detail --

        #region -- Functions --

        private bool CheckValidate()
        {
            error.Clear();
            bool flag = true;
            if (!Common.IsBlankTextBox(txtDeliveryAddress, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtDiameter, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtFabricWeight, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtGauge, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtKnittingMachine, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtWeightEcru, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtWeightFinEst, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtWhaleCourse, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtWidthEcru, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtWidthFinEst, "Required Field", error))
                flag = false;
            if (!Common.IsBlankTextBox(txtYarnLength, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboCustomerOrder, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboComposition, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboFabricType, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboOrderStatus, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboSupplier, "Required Field", error))
                flag = false;
            return flag;
        }

        private void CreateFormTitle()
        {
            ctrTitle.FormTitle = "KNITTING ORDER INFORMATIONS";
            ctrTitle.BackColor = System.Drawing.Color.White;
        }

        private void PushDataToForm(KnittingOrder order)
        {
            LoadCustomerOrder();
            LoadSupplier();
            LoadFabricType();
            LoadComposition();
            LoadOrderStatus();

            if (order.BelongToOrder != null)
            {
                cboCustomerOrder.SelectedValue = order.BelongToOrder.Id;
            }
            if (order.Composition != null)
            {
                cboComposition.SelectedValue = order.Composition.Id;
            }
            if (order.FabricType != null)
            {
                cboFabricType.SelectedValue = order.FabricType.Id;
            }
            if (order.OrderStatus != null)
            {
                cboOrderStatus.SelectedValue = order.OrderStatus.Id;
            }
            if (order.BelongToSupplier != null)
            {
                cboSupplier.SelectedValue = order.BelongToSupplier.Id;
                txtSupplierAddress.Text = order.BelongToSupplier.Address;
                txtSupplierName.Text = order.BelongToSupplier.SupplierName;
                txtSupplierPhone.Text = order.BelongToSupplier.Phone;
            }
            txtDeliveryAddress.Text = order.DeliveryAddress;

            txtDeliveryAddress.Text = order.DeliveryAddress;
            txtDiameter.Text = order.Diameter;
            txtFabricWeight.Text = order.FabricWeight.ToString();
            txtGauge.Text = order.Gauge;
            txtKnittingMachine.Text = order.KnittingMachine;
            txtWeightEcru.Text = order.ECRUWeight.ToString();
            txtWeightFinEst.Text = order.FinishEstimatedWeight.ToString();
            txtWhaleCourse.Text = order.WhaleCourse;
            txtWidthEcru.Text = order.ECRUWidth.ToString();
            txtWidthFinEst.Text = order.FinishEstimatedWidth.ToString();
            txtYarnLength.Text = order.LenghtOfYarnPer100Needles.ToString();

            dtpOrderDate.Value = order.OrderDate.Equals(DateTime.MinValue) ? DateTime.Today : order.OrderDate;

            LoadOrderDetailList();

            btnSave.Enabled = true;
        }

        private void LoadOrderList()
        {
            var orders = _repository.GetAll<KnittingOrder>().Where(k => k.BelongToKnittingOrderId == 0);
            IList<KnittingOrderModel> orderSource = new List<KnittingOrderModel>();

            // Get orders in selected month
            if (chkInMonth.Checked)
            {
                // Get order by supplier
                if (cboOrderStatusFilter.SelectedIndex > 0 && cboSupplierFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id && order.BelongToSupplier.Id == ((Supplier)cboSupplierFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else if (cboSupplierFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.BelongToSupplier.Id == ((Supplier)cboSupplierFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                // Get order by order status
                else if (cboOrderStatusFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
            }
            // Get all
            else
            {
                // Get order by supplier
                if (cboOrderStatusFilter.SelectedIndex > 0 && cboSupplierFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id && order.BelongToSupplier.Id == ((Supplier)cboSupplierFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else if (cboSupplierFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.BelongToSupplier.Id == ((Supplier)cboSupplierFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                // Get order by order status
                else if (cboOrderStatusFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else
                {
                    orderSource = (from order in orders
                                   select new KnittingOrderModel
                                   {
                                       Id = order.Id,
                                       SupplierName = order.BelongToSupplier.SupplierName,
                                       OrderDate = order.OrderDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
            }

            if (orderSource != null)
            {
                lvOrderList.Items.Clear();

                for (int i = 0; i < orderSource.Count; i++)
                {
                    ListViewItem item = lvOrderList.Items.Add(orderSource[i].Id.ToString());
                    item.Tag = orderSource[i];
                    item.SubItems.Add(orderSource[i].SupplierName);
                    item.SubItems.Add(orderSource[i].OrderDate.ToShortDateString());
                    item.SubItems.Add(orderSource[i].DeliveryStatus);
                }
            }
        }

        private void LoadOrderDetailList()
        {
            if (this._currentOrdersDetail != null)
            {
                lvOrderDetail.Items.Clear();
                for (int i = 0; i < this._currentOrdersDetail.Count; i++)
                {
                    ListViewItem item = lvOrderDetail.Items.Add(i + 1 + "");
                    item.Tag = this._currentOrdersDetail[i];
                    item.SubItems.Add(this._currentOrdersDetail[i].Weight.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].Length.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].Composition.CompostionName);
                    item.SubItems.Add(this._currentOrdersDetail[i].Note);
                    item.SubItems.Add(this._currentOrdersDetail[i].Price.ToString());
                }
            }
        }

        private void CreateOrder()
        {
            var order = this.CurrentOrder;
            order.BelongToOrder = (Order)cboCustomerOrder.SelectedItem;

            order.Composition = (Composition)cboComposition.SelectedItem;
            order.FabricType = (FabricType)cboFabricType.SelectedItem;
            order.OrderStatus = (OrderStatus)cboOrderStatus.SelectedItem;

            order.BelongToSupplier = (Supplier)cboSupplier.SelectedItem;
            order.DeliveryAddress = txtDeliveryAddress.Text.Trim();
            order.Diameter = txtDiameter.Text.Trim();

            double fabricWeight = 0;
            double.TryParse(txtFabricWeight.Text.Trim(), out fabricWeight);
            order.FabricWeight = fabricWeight;

            order.Gauge = txtGauge.Text;
            order.KnittingMachine = txtKnittingMachine.Text.Trim();

            double weightEcru = 0;
            double.TryParse(txtWeightEcru.Text.Trim(), out weightEcru);
            order.ECRUWeight = weightEcru;

            double weightFinEst = 0;
            double.TryParse(txtWeightFinEst.Text.Trim(), out weightFinEst);
            order.FinishEstimatedWeight = weightFinEst;

            order.WhaleCourse = txtWhaleCourse.Text.Trim();

            double widthEcru = 0;
            double.TryParse(txtWidthEcru.Text.Trim(), out widthEcru);
            order.ECRUWidth = widthEcru;

            double widthFinEst = 0;
            double.TryParse(txtWidthFinEst.Text.Trim(), out widthFinEst);
            order.FinishEstimatedWidth = widthFinEst;

            double yarnLength = 0;
            double.TryParse(txtYarnLength.Text.Trim(), out yarnLength);
            order.LenghtOfYarnPer100Needles = yarnLength;

            order.OrderDate = dtpOrderDate.Value;

            order.Details = this._currentOrdersDetail;
            try
            {
                _repository.Save<KnittingOrder>(order);
                LoadOrderList();
                MessageBox.Show("Save successfully.", "Warning", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void LoadSupplier()
        {
            try
            {
                var supplierData = _repository.GetAll<Supplier>();
                IList<Supplier> suppliers = new List<Supplier>();

                suppliers = (from c in supplierData
                             select new Supplier
                             {
                                 Id = c.Id,
                                 SupplierName = c.SupplierName,
                                 Address = c.Address,
                                 Phone = c.Phone
                             }).ToList();

                if (suppliers.Count > 0)
                {
                    cboSupplier.DataSource = suppliers;
                    cboSupplier.DisplayMember = "SupplierName";
                    cboSupplier.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadOrderStatus()
        {
            try
            {
                var orderStatusData = _repository.GetAll<OrderStatus>();
                IList<OrderStatus> orderStatus = new List<OrderStatus>();

                orderStatus = (from d in orderStatusData
                               select new OrderStatus
                               {
                                   Id = d.Id,
                                   OrderStatusName = d.OrderStatusName
                               }).ToList();

                if (orderStatus.Count > -1)
                {
                    cboOrderStatus.DataSource = orderStatus;
                    cboOrderStatus.DisplayMember = "OrderStatusName";
                    cboOrderStatus.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadFilterSupplier()
        {
            try
            {
                var supplierData = _repository.GetAll<Supplier>();
                IList<Supplier> suppliers = new List<Supplier>();
                IList<Supplier> suppliersResult = new List<Supplier>();

                suppliers = (from s in supplierData
                             select new Supplier
                             {
                                 Id = s.Id,
                                 SupplierName = s.SupplierName,
                                 Address = s.Address,
                                 Phone = s.Phone
                             }).ToList();

                if (suppliers.Count > 0)
                {
                    suppliersResult.Add(new Supplier { Id = -1, SupplierName = "-Select a supplier-", Address = string.Empty, Phone = string.Empty });

                    for (int i = 0; i < suppliers.Count; i++)
                    {
                        suppliersResult.Add(suppliers[i]);
                    }
                    cboSupplierFilter.DataSource = suppliersResult;
                    cboSupplierFilter.DisplayMember = "SupplierName";
                    cboSupplierFilter.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadFilterOrderStatus()
        {
            try
            {
                var orderStatusData = _repository.GetAll<OrderStatus>();
                IList<OrderStatus> orderStatusResult = new List<OrderStatus>();
                IList<OrderStatus> orderStatus = new List<OrderStatus>();

                orderStatus = (from d in orderStatusData
                               select new OrderStatus
                               {
                                   Id = d.Id,
                                   OrderStatusName = d.OrderStatusName
                               }).ToList();

                if (orderStatus.Count > 0)
                {
                    orderStatusResult.Add(new OrderStatus { Id = -1, OrderStatusName = "-Select status-" });
                    for (int i = 0; i < orderStatus.Count; i++)
                    {
                        orderStatusResult.Add(orderStatus[i]);
                    }
                    cboOrderStatusFilter.DataSource = orderStatusResult;
                    cboOrderStatusFilter.DisplayMember = "OrderStatusName";
                    cboOrderStatusFilter.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadCustomerOrder()
        {
            try
            {
                var customerOrderData = this._orderRepository.LoadAllOrder();
                IList<Order> customerOrder = new List<Order>();

                customerOrder = (from c in customerOrderData
                                 select new Order
                                 {
                                     Id = c.Id,
                                     Customer = c.Customer,
                                     DeliveryDate = c.DeliveryDate,
                                     DeliveryMethod = c.DeliveryMethod,
                                     Freight = c.Freight,
                                     IsDeliveredBefore = c.IsDeliveredBefore,
                                     NumberOfDateExtensionDelivery = c.NumberOfDateExtensionDelivery,
                                     OrderDate = c.OrderDate,
                                     OrderDetails = c.OrderDetails,
                                     OrderStatus = c.OrderStatus,
                                     PaymentMethod = c.PaymentMethod
                                 }).ToList();

                if (customerOrder.Count > -1)
                {
                    cboCustomerOrder.DataSource = customerOrder;
                    cboCustomerOrder.DisplayMember = "Id";
                    cboCustomerOrder.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadFabricType()
        {
            try
            {
                var data = _repository.GetAll<FabricType>();
                IList<FabricType> fabricTypeList = new List<FabricType>();

                fabricTypeList = (from d in data
                                  select new FabricType
                                 {
                                     Id = d.Id,
                                     FabricTypeName = d.FabricTypeName
                                 }).ToList();

                if (fabricTypeList.Count > -1)
                {
                    cboFabricType.DataSource = fabricTypeList;
                    cboFabricType.DisplayMember = "FabricTypeName";
                    cboFabricType.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadComposition()
        {
            try
            {
                var data = _repository.GetAll<Composition>();
                IList<Composition> compositions = new List<Composition>();

                compositions = (from d in data
                                select new Composition
                                  {
                                      Id = d.Id,
                                      CompostionName = d.CompostionName
                                  }).ToList();

                if (compositions.Count > -1)
                {
                    cboComposition.DataSource = compositions;
                    cboComposition.DisplayMember = "CompostionName";
                    cboComposition.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

         private void DoPrinting(KnittingOrder order, string filePath)
        {
            Font fBold = FontFactory.GetFont("Tahoma", 11, iTextSharp.text.Font.BOLD);
            Font fNormal = FontFactory.GetFont("Tahoma", 11);
            Font fNormalySmall = FontFactory.GetFont("Tahoma", 9);
            Font fBig = FontFactory.GetFont("Tahoma", 16, iTextSharp.text.Font.BOLD);

            var pdfFile = new Document(PageSize.A4);
            PdfWriter.GetInstance(pdfFile, new FileStream(filePath, FileMode.Create));

            pdfFile.Open();
            //Add Title
            Printing.AddTitleToPdf(pdfFile, "KNITTING ORDER", fBig);
            // Add Order Info
            KnittingOrderPrinting.AddOrderInfoToPdf(pdfFile, order, fNormal, fBold);
            // Add Supplier Info
            KnittingOrderPrinting.AddSupplierInfoToPdf(pdfFile, order.BelongToSupplier, fNormal, fBold);
            // Add Pattern's Technical Parameters
            KnittingOrderPrinting.AddTechnicalParametersToPdf(pdfFile, order, fNormal, fBold);
            // Add Estimated Knitting Machines
            KnittingOrderPrinting.AddEstimatedKnittingMachinesToPdf(pdfFile, order, fNormal, fBold);
            // Add Order detal
            KnittingOrderPrinting.AddOrderDetailToPdf(pdfFile, order.Details, fNormalySmall, fBold);
            // Add Signatures
            Printing.AddSignaturesToPdf(pdfFile, fBold, "Notes", "Customer Confirmation");
            pdfFile.Close();
        }

        #endregion -- Functions --

    }
}